package com.lujieni.netty.c4;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.embedded.EmbeddedChannel;

import java.nio.charset.StandardCharsets;

public class TestEmbeddedChannel {

    public static void main(String[] args) {

        ChannelHandler h1 = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                System.out.println("h1");
                ctx.fireChannelRead(msg); //交给下一个InboundHandler处理(否则handler就断开了)
            }
        };

        ChannelHandler h2 = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                System.out.println("h2");
                ctx.fireChannelRead(msg); //交给下一个InboundHandler处理(否则handler就断开了)
            }
        };

        ChannelHandler h3 = new ChannelOutboundHandlerAdapter() {
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                System.out.println("h3");
                super.write(ctx, msg, promise); //交给下一个OutboundHandler处理(否则handler就断开了)
            }
        };

        ChannelHandler h4 = new ChannelOutboundHandlerAdapter() {
            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                System.out.println("h4");
                super.write(ctx, msg, promise); //交给下一个OutboundHandler处理(否则handler就断开了)
            }
        };


        EmbeddedChannel embeddedChannel = new EmbeddedChannel(h1, h2, h3, h4);
        //embeddedChannel.writeInbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hello".getBytes()));
        embeddedChannel.writeOutbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hello".getBytes()));

    }


}
